//
//  PywLoginView.m
//  PywSdk
//
//  Created by Jade on 4/7/16.
//  Copyright © 2016 zero. All rights reserved.
//

#import "PywLoginView.h"
#import "PywLoginMainView.h"
#import "PywLoginGameView.h"
#import "PywLoginStatusView.h"
#import "PywMasonry.h"
#import "PywPlatformMain.h"
#import "PywNavgationController.h"
#import "PywPlatformMain.h"
#import "ApiClientConst.h"
#import "PywUser.h"
#import "PywPassportUtils.h"
#import "PywLogoutManger.h"
#import "PywSdk+login.h"
#import "PywCPNotifications.h"
#import "PywBindGetSMSCodeController.h"
#import "PywRegisterMainViewController.h"
#import "MutableDictionary.h"
#import "PywAppInfo.h"
#import "PywUnbundAlertView.h"
#import "PywFileManager.h"
#import "AppUtil.h"
#import "PywBuriedManager.h"
#import "PywNoticeView.h"
#import "LocalInfoUtil.h"

@interface PywLoginView()<PywUnbundAlertViewDelegate>
@property (nonatomic,strong) PywLoginMainView *loginMainView;
@property (nonatomic,strong) PywLoginGameView *loginGameView;
@property (nonatomic,strong) PywLoginStatusView *loginStatusView;
@property (nonatomic,strong) PywNoticeView *noticeView;

@property (nonatomic,strong) UIView *currentView;

@property (nonatomic,strong) NSArray *accountList;//游戏账号列表
@end
@implementation PywLoginView

- (instancetype)init
{
    self = [super init];
    if (self) {
        [PywAppInfo sharedAppInfo].hasLoginView = YES;
        self.backgroundColor = [UIColor colorWithWhite:0. alpha:.6];
        [self setUp];
        NSLog(@"进入登录页面");
        [PywBuriedManager manager].page_sn = @"1";
        [[PywBuriedManager manager] saveUserActionDataWithPageSn:@"1" actionSn:@"1" typeSn:@"1"];
    }
    return self;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


#pragma mark - setUp
- (void)setUp
{
    if([self isShowNotice])
        return;
    if ([self isCanAutoLogin]) {
        [self hasLogin];
    }else {
        [self loginMainViewToScreen];
    }
    
//    if ([PywPassportUtils passport].count > 0) {
//        PywUser *user = [[PywPassportUtils passport] firstObject];
//        if ((user.passport.length > 0 && user.password.length > 0)
//            && ![PywPlatformMain sharedPlatformMain].logouted) {
//            [self hasLogin];
//        }else {
//            [self loginMainViewToScreen];
//        }
//    }else {
//        [self loginMainViewToScreen];
//    }

    
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(didRegisterSuccess:)
                                                 name:DidRegisterSuccess
                                               object:nil];
    
}

/**
 *  判断是否要自动登录
 *
 *  @return return value description
 */
- (BOOL)isCanAutoLogin
{
    BOOL isAutoLogin = NO;
    NSString *loginAccount = [PywPlatformMain sharedPlatformMain].changeAccount;
    if ([PywPassportUtils passport].count > 0) {
        PywUser *user = [[PywPassportUtils passport] firstObject];
        if (user.passport.length > 0 && user.password.length > 0) {
            if (![PywPlatformMain sharedPlatformMain].logouted  || loginAccount.length > 1) {
                isAutoLogin = YES;
            }else {
                isAutoLogin = NO;
            }
        }else {
            isAutoLogin = NO;
        }
    }
    return isAutoLogin;
}

/**
 *  已经登录过的 自动登陆
 */
- (void)hasLogin
{
    [self addSubview:self.loginMainView];
    [self.loginMainView mas_makeConstraints:^(PywMASConstraintMaker *make) {
        make.center.offset(0);
        make.width.mas_equalTo(SCREEN_MIN_LENGTH * 0.85);
        NSInteger viewWidth = [UIScreen mainScreen].bounds.size.width >
        [UIScreen mainScreen].bounds.size.height ?
        [UIScreen mainScreen].bounds.size.height :
        [UIScreen mainScreen].bounds.size.width;
        viewWidth = MIN(viewWidth, 500);
        make.width.equalTo(@(viewWidth * 0.85));
        if (viewWidth%320 == 0 || viewWidth%480 == 0) {
            CGFloat height  = [PywAppInfo sharedAppInfo].appType == AppTypeFQ?0.65:0.75;
            make.height.equalTo(@(viewWidth * height));
        }else {
            CGFloat height  = [PywAppInfo sharedAppInfo].appType == AppTypeFQ?0.58:0.65;
            make.height.equalTo(@(viewWidth * height));
        }
    }];
    
    PywUser *user = [[PywPassportUtils passport] firstObject];
    [PywPlatformMain sharedPlatformMain].userName = user.passport;
    [PywPlatformMain sharedPlatformMain].passport_pwd = user.password;
    [self.loginMainView autoLoginPassport];
}

#pragma mark - Actions

/**
 *  通行证/游戏账号添加到主屏幕
 */
- (void)loginMainViewToScreen
{
    if (!_loginMainView) {
        [self.loginMainView add2SuperView:self];
    }
    if (![self.currentView isKindOfClass:[self.loginMainView class]]) {
        [self show:self.loginMainView stopAnimation:NULL];
    }
}

/**
 *  游戏账号登录View添加到主屏幕
 */
- (void)loginGameViewToScreen
{
    if (!_loginGameView) {
        [self.loginGameView add2SuperView:self];
    }
    
    [self show:self.loginGameView stopAnimation:NULL];
}
/**
 *  登录状态View添加到主屏幕
 *
 *  @param  登录状态===登录0||新建游戏账号1
 *  @param  登录状态view 显示的账号
 */
- (void)loginStstusViewToScreen
{
    if (!_loginStatusView) {
        [self.loginStatusView add2SuperView:self];
    }
    CGRect frame = self.loginStatusView.frame;
    frame.origin.y = -50;
    self.loginStatusView.frame = frame;
    [self showStatus:self.loginStatusView stopAnimation:NULL];
}



#pragma mark - getter Method

/**
 *  平台账号登陆界面
 *
 *  @return <#return value description#>
 */
- (PywLoginMainView *)loginMainView
{
    if (!_loginMainView) {
        _loginMainView = [[PywLoginMainView alloc] init];
        WEAK_SELF;
        /**
         *  账号登录成功
         *
         *  @param loginMainView loginMainView
         *  @param accountList   accountList
         */
        _loginMainView.loginPassportCompletion = ^(PywLoginMainView *loginMainView,NSArray *accountList) {
            STRONG_SELF(weakSelf);
            strongSelf.accountList = accountList;
            [strongSelf hide:strongSelf.loginMainView stopAnimation:^{
                [strongSelf loginStstusViewToScreen];
            }];
        };
        /**
         *  账号登录失败
         *
         *  @param loginMainView <#loginMainView description#>
         */
        _loginMainView.loginPassportFail = ^(PywLoginMainView *loginMainView) {
            STRONG_SELF(weakSelf);
            [strongSelf loginMainViewToScreen];
        };
        _loginMainView.loginVisitorCompletion = ^(PywLoginMainView *loginMainView) {
            [weakSelf dispose];
        };
    }
    return _loginMainView;
}
/**
 *  游戏账号登陆界面
 *
 *  @return <#return value description#>
 */
- (PywLoginGameView *)loginGameView
{
    if (!_loginGameView) {
        _loginGameView = [[PywLoginGameView alloc] initWithAccountList:self.accountList];
        WEAK_SELF;
        /**
         *  登陆|新建 游戏账号
         *
         *  @param loginGameView <#loginGameView description#>
         */
        _loginGameView.accountLoginCompletion = ^(PywLoginGameView *loginGameView) {
            STRONG_SELF(weakSelf);
            [strongSelf dispose];
        };
        _loginGameView.returnbackLoginCompletion = ^(PywLoginGameView *loginGameView) {
            STRONG_SELF(weakSelf);
            [strongSelf hide:strongSelf.loginGameView stopAnimation:^{
                [[PywLogoutManger manger] clearLogin];
                [strongSelf loginMainViewToScreen];
            }];
            
        };
    }
    return _loginGameView;
}

/**
 * @return true-需显示公告 false-不显示
 *
 **/
-(BOOL) isShowNotice{
    BOOL ret = NO;
    NSString * url = [PywAppInfo sharedAppInfo].notice_url;
    if(url && url.length){
        int32_t msgid = [[self getParamValueFromUrl:url paramName:@"id"] intValue];
        ret = ![LocalInfoUtil getMsgStatus:msgid];
        if(ret){
            [self.noticeView add2SuperView:self withUrl:url andMsgId:msgid];
        }
    }
    return ret;
}

//从url中截取参数
-(NSString *) getParamValueFromUrl:(NSString *)url paramName:(NSString *)paramName{
    if (![paramName hasSuffix:@"="]) {
        paramName = [NSString stringWithFormat:@"%@=", paramName];
    }
    
    NSString *str = nil;
    NSRange   start = [url rangeOfString:paramName];
    if (start.location != NSNotFound) {
        // confirm that the parameter is not a partial name match
        unichar  c = '?';
        if (start.location != 0) {
            c = [url characterAtIndex:start.location - 1];
        }
        if (c == '?' || c == '&' || c == '#') {
            NSRange     end = [[url substringFromIndex:start.location + start.length] rangeOfString:@"&"];
            NSUInteger  offset = start.location + start.length;
            str = end.location == NSNotFound ?
            [url substringFromIndex:offset] :
            [url substringWithRange:NSMakeRange(offset, end.location)];
            str = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        }
    }
    return str;
}

/**
 * 公告弹窗
 **/
-(PywNoticeView *) noticeView{
    if(!_noticeView){
        _noticeView = [[PywNoticeView alloc] init];
        WEAK_SELF;
        /**
         *  关闭界面
         */
        _noticeView.onViewClose = ^(PywNoticeView *noticeView) {
            STRONG_SELF(weakSelf);
            [strongSelf dispose];
        };
    }
    return _noticeView;
}


/**
 *  欢迎界面
 *
 *  @return <#return value description#>
 */
- (PywLoginStatusView *)loginStatusView
{
    if (!_loginStatusView) {
        _loginStatusView = [[PywLoginStatusView alloc] init];
        WEAK_SELF;
        /**
         *  其他方式登录
         *
         *  @param loginStautsView <#loginStautsView description#>
         */
        _loginStatusView.switchOtherLoginCompletion = ^(PywLoginStatusView *statusView) {
            STRONG_SELF(weakSelf);
            [strongSelf hide:strongSelf.loginStatusView stopAnimation:^{
                [strongSelf.loginStatusView removeFromSuperview];
                strongSelf.loginStatusView = nil;
                UserType account_type = [PywPlatformMain sharedPlatformMain].accountType;
                if (account_type == UserType_Passport) {
                    [strongSelf loginGameViewToScreen];
                }else {
                    [[PywLogoutManger manger] clearLogin];
                    [strongSelf loginMainViewToScreen];
                }
            }];
        };
        /**
         *  登录成功
         *
         *  @param loginStatusView <#loginStatusView description#>
         */
        _loginStatusView.loginCompletion = ^(PywLoginStatusView *statusView) {
            STRONG_SELF(weakSelf);
            strongSelf.currentView.hidden = YES;
            
            // 先判断，不弹出“实名认证”时，在判断弹出“绑定手机”。
            if ([PywPlatformMain sharedPlatformMain].accountType == UserType_Account
                && [PywPlatformMain sharedPlatformMain].passport.length == 0
                && ![PywPlatformMain sharedPlatformMain].is_verify_show
                && strongSelf != nil) {
                
                [strongSelf dialog];
            }else {
                [strongSelf dispose];
            }
        };
    }
    return _loginStatusView;
}
/// 弹出绑定对话框
- (void)dialog{
    if ([PywUnbundAlertView isOpenDialog]) {
        
        PywUnbundAlertView *alertView = [[PywUnbundAlertView alloc] initWithTitle:@"未绑定手机"
                                                                          message:@"忘记密码可用手机找回\n可登录所有朋友玩游戏"
                                                                     messageImage:@"img_emoji03"
                                                                         delegate:self
                                                                  sureButtonTitle:@"立即绑定"];
        [alertView show];
        // 保存当前弹出的时间
        [[PywFileManager manager] setFileValue:[NSNumber numberWithLong:[AppUtil getNowTimeStamp]] forFileKey:@"lastOpenDialogTime"];
    } else {
        [self dispose];
    }
}

#pragma mark - Public Method
/**
 *  添加LoginView
 *
 */
- (void)addLogin2keyWindow
{
    [[UIApplication sharedApplication].keyWindow.rootViewController.view addSubview:self];
    [self mas_makeConstraints:^(PywMASConstraintMaker *make) {
        make.top.left.right.bottom.offset(0);
    }];
}

#pragma mark - /******** 注册平台账号后跳转 **********/
/**
 *  通行证已注册，显示登录界面
 *
 *  @param aNotifivation <#aNotifivation description#>
 */
- (void)didRegisterSuccess:(NSNotification *)aNotification
{
    
    MutableDictionary *param = aNotification.object;
    NSString *password = [param objectForKey:@"password"];
    NSString *passport = [param objectForKey:@"passport"];
    BOOL is_fastRegister = [[param objectForKey:@"fastRegister"] boolValue];
    if (passport.length > 0) {
        [self loginMainViewToScreen];
        [self.loginMainView reloadLoginText:passport password:password];
    } else if (is_fastRegister == YES) {
        WEAK_SELF;
        [self hide:self.loginMainView stopAnimation:^{
            STRONG_SELF(weakSelf);
            [strongSelf loginStstusViewToScreen];
        }];
    } else {
        [self dispose];
    }
    
}

#pragma mark - PywUnbundAlertViewDelegate
/**
 *  select Button
 *
 *  @param alertView   this AlertView
 *  @param buttonIndex select  ButtonIndex
 */
- (void)bundAlertView:(PywUnbundAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    [self dispose];
    if (buttonIndex == 1) {
        [[PywBuriedManager manager] saveUserActionDataWithPageSn:@"3" actionSn:@"9" typeSn:@"3"];
        PywBindGetSMSCodeController *getCodeView = [[PywBindGetSMSCodeController alloc] init];
        PywNavgationController *nav = [[PywNavgationController alloc] initWithRootViewController:getCodeView];
        [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:nav animated:YES completion:NULL];
    }else{
        [[PywBuriedManager manager] saveUserActionDataWithPageSn:@"3" actionSn:@"8" typeSn:@"3"];
    }
}



#pragma mark - =====Delegate End====
/**
 *  键盘弹起
 *
 *  @param aNotification <#aNotification description#>
 */
- (void)keyboardWillShow:(NSNotification *)aNotification
{
    CGRect keyboardFrame = [[aNotification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    NSNumber *duration = [aNotification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curv = [aNotification.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    
    CGRect frame = self.currentView.frame;
    CGFloat orginMaxY = CGRectGetMaxY(frame);
    if (orginMaxY > CGRectGetMinY(keyboardFrame)) {
        if (!IS_IPAD) {
            frame.origin.y = CGRectGetHeight(self.frame) - (CGRectGetHeight(keyboardFrame) + 190.f);
        } else {
            frame.origin.y = CGRectGetHeight(self.frame) - (CGRectGetHeight(keyboardFrame) + 230.f);
        }
    }
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:duration.integerValue];
    [UIView setAnimationCurve:curv.integerValue];
    
    self.currentView.frame = frame;
    [UIView commitAnimations];
}

/**
 *  键盘隐藏
 *
 *  @param aNotification <#aNotification description#>
 */
- (void)keyboardWillHide:(NSNotification *)aNotification
{
    NSNumber *duration = [aNotification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curv = [aNotification.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:duration.integerValue];
    [UIView setAnimationCurve:curv.integerValue];
    self.currentView.center = self.center;
    [UIView commitAnimations];
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self endEditing:YES];
    if (![PywPlatformMain sharedPlatformMain].logined
        && [PywPlatformMain sharedPlatformMain].canHideLogin) {
        [self dispose];
        
        // 关闭时才发送登录完成的通知
        NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
        // 发送登录完成的通知
        [dict setObject:[NSNumber numberWithInt:PYW_LOGIN_STATE_CANCEL] forKey:@"result"];
        [dict setObject:@"取消登录" forKey:@"info"];
        // 发送通知
        [[NSNotificationCenter defaultCenter] postNotificationName:kPywCPLoginNotification object:nil userInfo:dict];
    }
}


#pragma mark - Show|Hide
- (void)show:(UIView *)theView stopAnimation:(StopAnimation)stopAnimation
{
    self.currentView = theView;
    __block UIView *mainView = theView;
    mainView.transform = CGAffineTransformMakeScale(0.9f, 0.9f);
    [UIView animateWithDuration:.2f
                          delay:0 options:UIViewAnimationOptionCurveEaseIn
                     animations:^{
                         mainView.alpha = 1;
                         mainView.transform = CGAffineTransformMakeScale(1.f, 1.f);
                     } completion:^(BOOL finished) {
                         if (stopAnimation) {
                             stopAnimation();
                         }
                     }];
}

- (void)hide:(UIView *)theView stopAnimation:(StopAnimation)stopAnimation
{
    self.currentView = theView;
    __block UIView *mainView = theView;
    [UIView animateWithDuration:.2f
                          delay:0 options:UIViewAnimationOptionCurveEaseOut
                     animations:^{
                         mainView.alpha = 0;
                         mainView.transform = CGAffineTransformMakeScale(0.9f, 0.9f);
                     } completion:^(BOOL finished) {
                         if (stopAnimation) {
                             stopAnimation();
                         }
                     }];
}
/**
 *  显示登录中页面
 *
 *  @param theView       <#theView description#>
 *  @param stopAnimation <#stopAnimation description#>
 */
- (void)showStatus:(UIView *)theView stopAnimation:(StopAnimation)stopAnimation
{
    self.currentView = theView;
    __block UIView *mainView = theView;
    __block CGRect frame = mainView.frame;
    [UIView animateWithDuration:.2f
                          delay:0 options:UIViewAnimationOptionCurveEaseIn
                     animations:^{
                         mainView.alpha = 1;
                         frame.origin.y = 0;
                         mainView.frame = frame;
                     } completion:^(BOOL finished) {
                         if (stopAnimation) {
                             stopAnimation();
                         }
                     }];
}



/**
 *  loginView dispose
 */
- (void)dispose
{
    NSLog(@"%s",__FUNCTION__);
    [PywBuriedManager manager].page_sn = @"";
//    [[PywBuriedManager manager] saveUserActionDataWithPageSn:@"1" actionSn:@"2" typeSn:@"2"];
    if (_loginStatusView) {
        [self.loginStatusView updateStopBindingAlert:YES];
    }
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:.5f
                     animations:^{
                         weakSelf.alpha = 0;
                     } completion:^(BOOL finished) {
                         [self removeFromSuperview];
                         [PywAppInfo sharedAppInfo].hasLoginView = NO;
                     }];
    
}


@end

